package com.wxq.ams.backup.utils;

import org.apache.ibatis.jdbc.ScriptRunner;

import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;

import org.apache.ibatis.io.Resources;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SqlExecUtils {
    private static final Logger logger = LoggerFactory.getLogger(SqlExecUtils.class);

    /**
     * SQL文件执行导入
     *
     * @param dbHost       地址
     * @param dbName       数据库名
     * @param userName     用户名
     * @param userPassword 密码
     * @param dbPort       端口
     * @return
     */
    public static boolean sqlExec(String dbHost, String dbName, String userName, String userPassword, String dbPort, String sqlFile) {
        try {
            logger.info("开始数据库连接。。。");
            Connection conn = getMySqlConnection(dbHost, dbName, userName, userPassword, dbPort);
            ScriptRunner runner = new ScriptRunner(conn);
            Resources.setCharset(Charset.forName("UTF-8")); //设置字符集,不然中文乱码插入错误
            runner.setLogWriter(null);//设置是否输出日志
            // 绝对路径读取
//          Reader read = new FileReader(new File("f:\\test.sql"));
            // 从class目录下直接读取
//           Reader read = Resources.getResourceAsReader("test.sql");
//            ClassPathResource resource = new ClassPathResource("backup" + File.separator + "test.sql");// 获取文件流
//            File file = resource.getFile();
            logger.info("开始读取SQL文件。。。");
            Reader read = new FileReader(new File(sqlFile));
            runner.runScript(read);
            runner.closeConnection();
            conn.close();
            logger.info("SQL文件执行成功");
            return true;
        } catch (Exception e) {
            logger.error("SQL文件执行失败，原因：" + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @return
     * @throws Exception
     * @功能描述： 获取数据库连接
     */
    public static Connection getMySqlConnection(String dbHost, String dbName, String userName, String userPassword, String dbPort) throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName + "?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8";
        return DriverManager.getConnection(url, userName, userPassword);
    }

}